<template>
  <el-card class="application-form-container">
    <template #header>
      <div class="card-header">
        <span class="header-title">寒衣申请填写</span>
      </div>
    </template>

    <!-- 批次信息展示 -->
    <el-card v-if="batchInfo" class="batch-info-card" shadow="never">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span class="info-title">可申请批次信息</span>
          <el-tag v-if="studentInfo" :type="isNewStudent ? 'success' : 'info'" size="large">
            {{ studentInfo.grade }}级 {{ isNewStudent ? '新生' : '老生' }}
          </el-tag>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="学年">
          {{ batchInfo.academicYear }}学年
        </el-descriptions-item>
        <el-descriptions-item label="困难等级">
          {{ formatDifficultyLevel(batchInfo.difficultyLevel) }}
        </el-descriptions-item>
        <el-descriptions-item label="申请开始时间">
          {{ formatDateTime(batchInfo.applyStart) }}
        </el-descriptions-item>
        <el-descriptions-item label="申请截止时间">
          {{ formatDateTime(batchInfo.applyDeadline) }}
        </el-descriptions-item>
        <el-descriptions-item label="登记截止时间" :span="2">
          {{ formatDateTime(batchInfo.registerDeadline) }}
        </el-descriptions-item>
      </el-descriptions>
      
      <!-- 新生提示 -->
      <el-alert
        v-if="isNewStudent"
        type="info"
        :closable="false"
        show-icon
        style="margin-top: 16px;"
      >
        <template #title>
          <span>您是{{ studentInfo.grade }}级新生，申请理由可选填</span>
        </template>
      </el-alert>
    </el-card>

    <!-- 暂无可申请批次提示 -->
    <el-empty 
      v-else-if="!loading" 
      description="暂无可申请的批次" 
      :image-size="200"
    />

    <!-- 申请表单 -->
    <el-form
      v-if="batchInfo"
      ref="applicationFormRef"
      :model="applicationForm"
      :rules="rules"
      label-width="120px"
      class="application-form"
    >
      <el-form-item prop="applyReason">
        <template #label>
          <span>申请理由</span>
          <span v-if="isNewStudent" style="color: #909399; font-size: 12px; margin-left: 8px;">（新生可选填）</span>
          <span v-else style="color: #f56c6c; font-size: 12px; margin-left: 8px;">*</span>
        </template>
        <el-input
          v-model="applicationForm.applyReason"
          type="textarea"
          :rows="8"
          :placeholder="isNewStudent ? '请说明您的申请理由（新生可选填，至少10个字）' : '请详细说明您的申请理由（必填，至少10个字）'"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          提交申请
        </el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { _getMyBatch } from '@/api/batch'
import { _saveApplication, _getStudentByUserId } from '@/api/application'
import { _getCurrentUser } from '@/api/user'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const submitting = ref(false)
const batchInfo = ref(null)
const studentInfo = ref(null)
const applicationFormRef = ref(null)

// 表单数据
const applicationForm = reactive({
  applyReason: ''
})

// 判断是否为新生（年级 === 批次申请开始年份）
const isNewStudent = computed(() => {
  if (!batchInfo.value || !studentInfo.value) return false
  
  // 获取批次申请开始时间的年份
  const applyStartYear = new Date(batchInfo.value.applyStart).getFullYear()
  
  // 学生年级（入学年份）
  const studentGrade = studentInfo.value.grade
  
  // 如果年级等于批次申请开始年份，则为新生
  return studentGrade === applyStartYear
})

// 动态验证规则
const rules = computed(() => {
  // 自定义验证器
  const validateApplyReason = (rule, value, callback) => {
    if (isNewStudent.value) {
      // 新生：可选填，但如果填写了至少要10个字
      if (value && value.trim().length > 0 && value.trim().length < 10) {
        callback(new Error('申请理由至少10个字'))
      } else {
        callback()
      }
    } else {
      // 老生：必填且至少10个字
      if (!value || value.trim().length === 0) {
        callback(new Error('请输入申请理由'))
      } else if (value.trim().length < 10) {
        callback(new Error('申请理由至少10个字'))
      } else {
        callback()
      }
    }
  }

  return {
    applyReason: [
      { validator: validateApplyReason, trigger: 'blur' }
    ]
  }
})

// 格式化困难等级
const formatDifficultyLevel = (level) => {
  const levelMap = {
    0: '一般困难',
    1: '困难',
    2: '特别困难'
  }
  return levelMap[level] || '未知'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取当前学生信息
const getStudentInfo = async () => {
  try {
    // 先获取当前用户信息
    const userRes = await _getCurrentUser()
    if (userRes && userRes.code === 200) {
      const userId = userRes.data.user.id
      
      // 根据用户ID获取学生信息
      const studentRes = await _getStudentByUserId(userId)
      if (studentRes && studentRes.code === 200) {
        studentInfo.value = studentRes.data.student
      }
    }
  } catch (error) {
    console.error('获取学生信息失败:', error)
  }
}

// 获取批次信息
const getBatchInfo = async () => {
  loading.value = true
  try {
    const res = await _getMyBatch()
    if (res && res.code === 200) {
      batchInfo.value = res.data.batch
      
      // 检查批次是否在有效期内
      if (batchInfo.value) {
        const now = new Date()
        const applyStart = new Date(batchInfo.value.applyStart)
        const applyDeadline = new Date(batchInfo.value.applyDeadline)
        
        if (now < applyStart) {
          ElMessage.warning('申请尚未开始')
        } else if (now > applyDeadline) {
          ElMessage.warning('申请已截止')
        }
      }
    } else {
      ElMessage.warning(res.message || '获取批次信息失败')
    }
  } catch (error) {
    console.error('获取批次信息失败:', error)
    ElMessage.error('获取批次信息失败')
  } finally {
    loading.value = false
  }
}

// 提交申请
const handleSubmit = async () => {
  // 表单验证
  if (!applicationFormRef.value) return
  
  await applicationFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    // 检查批次是否有效
    const now = new Date()
    const applyStart = new Date(batchInfo.value.applyStart)
    const applyDeadline = new Date(batchInfo.value.applyDeadline)
    
    if (now < applyStart) {
      ElMessage.warning('申请尚未开始，请在申请开始时间后提交')
      return
    }
    
    if (now > applyDeadline) {
      ElMessage.warning('申请已截止，无法提交')
      return
    }
    
    // 确认提交
    try {
      await ElMessageBox.confirm(
        '确认提交申请吗？提交后将进入审核流程。',
        '提示',
        {
          confirmButtonText: '确认提交',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      
      submitting.value = true
      
      // 构造申请数据
      const applicationData = {
        batchId: batchInfo.value.id,
        applyReason: applicationForm.applyReason,
        applyTime: new Date().toISOString()
      }
      
      const res = await _saveApplication(applicationData)
      
      if (res && res.code === 200) {
        ElMessage.success('申请提交成功')
        // 跳转到我的申请页面
        setTimeout(() => {
          router.push('/application/myApplication')
        }, 1000)
      } else {
        ElMessage.error(res.message || '申请提交失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('提交申请失败:', error)
        ElMessage.error(error.message || '申请提交失败')
      }
    } finally {
      submitting.value = false
    }
  })
}

// 重置表单
const handleReset = () => {
  applicationFormRef.value?.resetFields()
}

// 页面加载时获取学生信息和批次信息
onMounted(async () => {
  await getStudentInfo()
  await getBatchInfo()
})
</script>

<style scoped lang="scss">
.application-form-container {
  margin: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .header-title {
      font-size: 18px;
      font-weight: bold;
      color: #303133;
    }
  }
  
  .batch-info-card {
    margin-bottom: 30px;
    
    .info-title {
      font-size: 16px;
      font-weight: 600;
      color: #409eff;
    }
  }
  
  .application-form {
    margin-top: 30px;
    max-width: 800px;
    
    :deep(.el-textarea__inner) {
      font-family: inherit;
    }
  }
}
</style>

